#!/user/bin/env python
# coding:utf-8
"""
Author myYouTh
Date:2020/2/20 002014:23
Desc: 接口自动化测试，getRegionCountry接口的封装：获取国外国家名称和与之对应的ID
"""


import copy
import requests
from requests.exceptions import ConnectTimeout
from utils.dataDescriptor import StrDataDescriptor, DictDataDescriptor


class APICommon(object):
    """测试接口初始化的工作"""
    def __init__(self, requestmethod: str, requesthost: str, requestinterface: str, requestheader: dict, requestdata: dict):
        """
        初始化getRegionCountry接口的请求
        :param requestmethod: 请求的方法，get ,post, soup
        :param requesthost: 请求的主机地址
        :param requestinterface: 请求的接口名字
        :param requestheader: 请求的头部信息
        :param requestdata: 请求的提交数据。果然请求时的提交数据为空时，请传递一个空字典
        """
        self._requestmethod = requestmethod
        self._requesthost = requesthost
        self._interfacename = requestinterface
        self._requestheader = requestheader
        self._requestdata = requestdata

        # 用于参数类型检查的变量是类变量，没有实例变量，因为将类变量的值添加到实例变量中
        self.__dict__['method'] = copy.deepcopy(self._requestmethod)
        self.__dict__["host"] = copy.deepcopy(self._requesthost)
        self.__dict__["interface"] = copy.deepcopy(self._interfacename)
        self.__dict__["header"] = copy.deepcopy(self._requestheader)

        if (not self._requestdata) and (self._requestmethod == "GET"):
            self.__dict__["data"] = None
        else:
            self.__dict__["data"] = copy.deepcopy(self._requestdata)


class APIGetRegionCountry(APICommon):
    """
    天气预报服务：getRegionCountry接口封装，获取国外国家名称和与之对应的ID
    输入参数：无
    返回数据：xml格式,包含国家名称和ID
    """

    _requestmethod = StrDataDescriptor()
    _requesthost = StrDataDescriptor()
    _interfacename = StrDataDescriptor()
    _requestheader = DictDataDescriptor()
    _requestdata = DictDataDescriptor()

    @property
    def method(self):
        self._dict_length()
        try:
            return self.__dict__["method"]
        except KeyError:
            raise NameError(f"{self.__str__()}类的实例的键不存在")

    @property
    def host(self):
        self._dict_length()
        try:
            return self.__dict__["host"]
        except KeyError:
            raise NameError(f"{self.__str__()}实例的键不存在")

    @property
    def interface(self):
        self._dict_length()
        try:
            return self.__dict__["interface"]
        except KeyError:
            raise NameError(f"{self.__str__()}实例的键不存在")

    @property
    def header(self):
        self._dict_length()
        try:
            return self.__dict__["header"]
        except KeyError:
            raise NameError(f"{self.__str__()}实例的键不存在")

    @property
    def data(self):
        self._dict_length()
        try:
            return self.__dict__["data"]
        except KeyError:
            raise NameError(f"{self.__str__()}实例的键不存在")

    def _dict_length(self):
        """
        检查实例变量是否增加
        :return:
        """
        if len(self.__dict__) == 5:
            pass
        else:
            raise NameError(f"{self.__str__()}类的实例变量过多")

    def url(self) -> str:
        """
        请求地址
        :return:
        """
        return self.host + "/" + self.interface

    def __str__(self):
        return self.__class__.__name__

    __repr__ = __str__

    def request(self):
        """向getRegionCountry接口发送请求，获取数据，其中数据格式为xml"""
        response_object = None
        _url = self.url()
        try:
            if self.method.upper() == 'GET':
                response_object = requests.request(method=self.method, url=_url, header=self.header, params=self.data)
            elif self.method.upper() == "POST":
                response_object = requests.request(method=self.method, url=_url, headers=self.header, data=self.data)
            elif self.method.upper() == "SOAP":
                pass
        except ConnectTimeout:
            raise ConnectTimeout
        else:
            # 响应内容转化为中文编码
            response_object.encoding = "utf-8"
            return response_object
        finally:
            pass

    def __del__(self):
        del self

